﻿using System;
using System.Collections.Generic;
using System.IO;
using Rabbit.Logic;
using RabbitShop.Code;
using Raven.Imports.Newtonsoft.Json;

namespace RabbitShop.Action
{
    public partial class UserAddress : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string uid = string.Empty;
            if (Request.Cookies[Constant.CookieName] != null)
            {
                uid = Request.Cookies[Constant.CookieName].Values[Constant.CookieUid];
                if (string.IsNullOrEmpty(uid)) Response.Redirect("~/UI/UserLogon.aspx");
            }
            else
            {
                Response.Redirect("~/UI/UserLogon.aspx");
            }

            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            if (!string.IsNullOrEmpty(postContent))
            {
                try
                {
                    Address item = JsonConvert.DeserializeObject<Address>(postContent);
                    
                    if (!string.IsNullOrEmpty(uid))
                    {
                        Customer customer = RabbitUse.GetCustomerById(Db.Store, uid);

                        int addressId;
                        string aid = Request["aid"];
                        if (int.TryParse(aid, out addressId))
                        {
                            if (addressId < customer.AddressList.Count)
                            {
                                customer.AddressList[addressId] = item;
                                item.Id = addressId.ToString();
                            }
                        }
                        else
                        {
                            if (customer.AddressList == null || customer.AddressList.Count == 0)
                            {
                                customer.AddressList = new List<Address>() { item };
                            }
                            else
                            {
                                customer.AddressList.Add(item);
                            }
                            item.Id = (customer.AddressList.Count - 1).ToString();
                        }
                        
                        RabbitUse.AddOrUpdateCustomer(Db.Store, customer);

                        Response.Write("true");
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }

            }
            else
            {

                Response.Write("false");
            }
        }
    }
}